package com.woniuxy.service;

import com.woniuxy.pojo.LoginSysLog;
import com.woniuxy.pojo.User;
import com.woniuxy.util.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Aspect
@Component
public class WebLogAspect {
    @Autowired
    LoginSysLogService loginSysLogService;
    private ThreadLocal<Long> startTime = new ThreadLocal<>();
    private static final ThreadLocal<Date> beginTimeThreadLocal =
            new NamedThreadLocal<Date>("ThreadLocal beginTime");

    //使用@Pointcut定义一个切入点，可以是一个规则表达式，比如下例中某个package下的所有函数，也可以是一个注解等。
    @Pointcut("execution(public * com.woniuxy.controller.LoginController.*(..))")
    public void webLog() {
    }

    //使用@Before在切入点开始处切入内容
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        LoginSysLog loginsysLog = new LoginSysLog();
        if (session.getAttribute("USER_SESSION") != null) {
            User user = (User) session.getAttribute("USER_SESSION");
            String username = user.getRealname();
            //请求用户名
            loginsysLog.setUsername(username);

            //请求ip地址
            loginsysLog.setIp(request.getRemoteAddr());
            //请求方式
            loginsysLog.setHttpMethod(request.getMethod());
            //请求类
            loginsysLog.setClassMethod(joinPoint.getSignature().getName());
            String url = (request.getRequestURL().toString());
            if (StringUtils.isNotBlank(request.getQueryString())) {
                url += "?" + request.getQueryString();
            }
            //url
            loginsysLog.setUrl(url);
            loginsysLog.setStarttime(new Date());

/*
           if (request.getMethod().equals("POST")) {
                if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
                    List<Object> o = new ArrayList<>();
                    for (Object arg : joinPoint.getArgs()) {
                        ObjectMapper mapper = new ObjectMapper();

                        try {
                            o.add(mapper.writeValueAsString(arg));
                        } catch (Exception ex) {

                        }

                    }
                    //？
                    sysLog.setArgs(Arrays.toString(o.toArray()));
                }
                logService.saveLog(sysLog);
            }*/
            loginSysLogService.saveLog(loginsysLog);



            // 记录下请求内容
           /* log.info(sysLog.toString());
            log.info("请求HTTP_METHOD : " + request.getMethod());
            log.info("请求IP : " + request.getRemoteAddr());
            log.info("请求CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("请求参数值 : " + Arrays.toString(joinPoint.getArgs()));
            log.info("现在时间" + new Date());
            log.info("用户名" + username);
            log.info("url" + url);*/

        }

    }
    //使用@AfterReturning在切入点return内容之后切入内容（可以用来对处理返回值做一些加工处理）
    @AfterReturning(returning = "ret", pointcut = "webLog()")
     public void doAfterReturning(Object ret) throws Throwable {
    // 处理完请求，返回内容
      //  log.info("响应RESPONSE : " + ret);
      //  log.info("响应时间SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));

    }



}